const Router = require('koa-router');
const router = new Router();
const {db, QueryTypes} = require("../../models/db");
const {xe} = require("../../tools/tool");

// 保存送货路线区域
router.post('/deliver/backList', async ctx => {
    let tenantId = ctx.user.tenantId;
    let code = ctx.request.body.code;
    let arr = code.split('-')
    if(arr.length !== 2) return ctx.err('二维码识别错误')
    let invoice = await db.models['vMain'].findOne({
        where: {
            tenantId,
            id: arr[1]
        }
    })
    if(!invoice) return ctx.err('未找到单据')
    // 如果有关联退货
    let relsql = `select count(*) total from invoice_back a inner join invoice b on a.tenantId=b.tenantId and a.tenantId=${tenantId} and a.oldIid=${invoice.id} and a.iid=b.id 
        where billState<>'del' `
    let relmodl = await db.query(relsql, {type: QueryTypes.SELECT, plain: true})
    if(relmodl.total > 0) {
        return ctx.err('该票据已做过关联退货')
    }
    let buId = invoice.buId;
    let buName = invoice.buName;
    let address = invoice.address;
    let arrearsReal = invoice.arrearsReal;
    let billNo = invoice.billNo;
    if(!buId || !buName) return ctx.err('不能识别的终端名称')

    // 最近退货的商品
    let back = `select invId from 
        (
        SELECT max(a.id) id,a.invId from v_main_info a inner join invoice b on a.tenantId=b.tenantId and a.iid=b.id inner join goods_back c on a.tenantId=c.tenantId and a.invId=c.invId where a.tenantId=${tenantId} GROUP BY a.invId
        ) a `
    let ids = []
    let lists = await db.query(back, {type: QueryTypes.SELECT})
    lists.map(row => {
        ids.push(row.invId)
    })
    let notin = await db.query( `select invId from goods_back where tenantId=${tenantId} and invId not in (${ids.join(',')}) `, {type: QueryTypes.SELECT})
    notin.map(row => {
        ids.join(row.invId)
    })
    if (ids.length === 0) return ctx.err('还没有设置要退货的包装物信息,请在 销售->快速退包装物 功能中 设置')
    let goods = await db.query(`select a.*,b.price,concat('1*',spec) specs from (select id,name,spec,unit1 unit,unit1,unit2 from v_goods where tenantId=${tenantId} and id in(${ids.join(',')})) a 
left join goods_back b on a.id=b.invId `,{type: QueryTypes.SELECT})

    let storage = await db.models['storage'].findOne({
        where: {
            tenantId,
            name:'默认仓库'
        }
    })
    goods.map(row => {
        row.calNum = row.spec
        row.price = xe.toFixed(row.price, 2)
        row.locationId = storage.id
        row.locationName = storage.name
    })
    return ctx.suc('', {
        billId: invoice.id,
        buId,
        buName,
        billNo,
        address,
        arrearsReal,
        locationId: storage.id,
        locationName: '默认仓库',
        list: goods
    });
})
router.post('/deliver/billHasBack', async ctx => {
    let has = await db.models['invoiceBack'].findOne({
        where: {
            tenantId: ctx.user.tenantId,
            oldIid: ctx.request.body.billId
        }
    })
    // if(has) return ctx.suc('该票据已做过退货,是否还要继续？')
    if(has) return ctx.err('该票据已做过退货。')
    return ctx.suc('')
})
module.exports = router;
